package com.binyouwei.udp_lib.factory;

import android.util.Log;

import androidx.annotation.NonNull;

import com.binyouwei.udp_lib.ReceiveMessageInterface;
import com.binyouwei.udp_lib.SingleThreads;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * @author 宾有为
 * @date 2024/6/11 20:05
 * @link https://blog.csdn.net/baidu_41616022?type=blog
 * @describe：
 **/
public class BroadcastFactory implements UdpFactory {
    final int port = 6666;
    final String TAG = getClass().getSimpleName();
    boolean isFinish = false;

    @Override
    public void initUdp() {
        isFinish = true;
    }

    @Override
    public void destroyUdp() {
        isFinish = false;
    }

    @Override
    public void sendMessage(@NonNull String ip, @NonNull String message) {
        SingleThreads.getInstance().execute(() -> {
             broadcastExample1(ip,message);
            // broadcastExample2(message);
        });
    }

    /**
     * 广播例子1
     * @param ip
     * @param message
     */
    private void broadcastExample1(String ip, String message) {
        try {
            byte[] bytes = message.getBytes();
            // 有限广播 ip 一般为 255.255.255.255
            InetAddress inet = InetAddress.getByName(ip);
            DatagramPacket packet = new DatagramPacket(bytes, bytes.length, inet, port);
            DatagramSocket datagramSocket = new DatagramSocket();
            datagramSocket.send(packet);
            Log.e(TAG, "发送广播成功，message：" + message);
        } catch (IOException e) {
            Log.e(TAG, "发送广播失败，message：" + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 广播例子 2
     * @param message
     */
    private void broadcastExample2(String message) {
        try {
            // 创建DatagramSocket实例
            DatagramSocket socket = new DatagramSocket();
            // 设置广播权限
            socket.setBroadcast(true);
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = networkInterfaces.nextElement();
                // 遍历接口上的所有地址，只广播IPV4地址
                for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) {
                    InetAddress broadcast = interfaceAddress.getBroadcast();
                    // 判断是否为IPV4地址
                    if (broadcast instanceof Inet4Address) {
                        // 将字符串转换为字节数组
                        byte[] buffer = message.getBytes();
                        // 创建DatagramPacket
                        DatagramPacket packet = new DatagramPacket(buffer, buffer.length, broadcast, port);
                        // 发送广播
                        socket.send(packet);
                        Log.e(TAG, "发送广播成功，message：" + message);
                    }
                }
            }
            socket.close();
        } catch (IOException e) {
            Log.e(TAG, "发送广播失败，message：" + e.getMessage());
            throw new RuntimeException(e);
        }
    }

    @Override
    public void onReceiveMessageListener(@NonNull String ip, @NonNull ReceiveMessageInterface receiveMessage) {
        SingleThreads.getInstance().execute(() -> {
            try {
                // 创建缓冲区以接收数据
                byte[] receiveData = new byte[1024];
                DatagramSocket socket = new DatagramSocket(port);
                socket.setBroadcast(true);
                while (isFinish) {
                    // 创建DatagramPacket来接收数据
                    DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                    // 接收广播消息
                    socket.receive(receivePacket);
                    // 处理接收到的数据
                    String message = new String(receivePacket.getData(), 0, receivePacket.getLength());
                    receiveMessage.onReceiveMessageListener(message);
                    Log.e(TAG, "广播收到一条消息，message：" + message);
                }
                socket.close();
            } catch (IOException e) {
                Log.e(TAG, "广播接收消息失败，message：" + e.getMessage());
                throw new RuntimeException(e);
            }
        });
    }
}
